package com.vecharm.app.manager

import android.util.Log
import com.google.gson.Gson
import com.ling.sdk.live.LiveManager
import com.ling.sdk.utils.delayed
import com.ling.sdk.utils.post
import com.vecharm.app.api.API
import com.vecharm.app.utils.getService
import com.vecharm.app.utils.request

const val MAX_REQUEST_COUNT = 360 // 360 * 5 = 1800 刚好30分钟

object SessionManager {

    private var requestCount = 0

    var callBack: ((Boolean, String?) -> Unit)? = null

    fun request() {
        requestCount++

        getService<API>().getSession().request {
            onSuccess = {
                Log.e("SessionLog", Gson().toJson(it))
                it.save()
                callBack?.invoke(true, it.desc)
                stop()
            }

            onErrorMessage = { code, error ->

                Log.e("SessionLog", "$error[$code]")

                callBack?.invoke(false, "$error[$code]")

                if (requestCount < MAX_REQUEST_COUNT) LiveManager.handler("Session", true) delayed 5 * 1000 post { request() }

            }
        }

    }

    private fun stop() {
        requestCount = MAX_REQUEST_COUNT
    }


}